package com.nakaikensuke.SNE;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import com.nakaikensuke.tools.MimeUtilities;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;

public class IconCacheManager {
	private PackageManager _manager = null;
	private HashMap<String, Drawable> _iconCache = null;

	public IconCacheManager(PackageManager manager) {
		_manager = manager;
		_iconCache = new HashMap<String, Drawable>();
	}
	
	public Drawable getIcon(String fileName) {
		if(fileName == null)
			return null;
		
		String mimeType = MimeUtilities.getMimeType(fileName);
		if(mimeType == null)
			return null;
		
		if(_iconCache.containsKey(mimeType))
			return _iconCache.get(mimeType);
		
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(fileName));
		intent.setDataAndType(uri, mimeType);
		
		List<ResolveInfo> list = _manager.queryIntentActivities(
													intent,
													PackageManager.MATCH_DEFAULT_ONLY);
		
		if(list == null || list.size() == 0)
			return null;
		
		Drawable drawable = list.get(0).loadIcon(_manager);
		_iconCache.put(mimeType, drawable);
		
		return drawable;
	}
}
